package cn.swenty.backstage.framework.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import cn.swenty.backstage.framework.common.FormMap;
import cn.swenty.backstage.framework.database.annotation.TableSeg;
import cn.swenty.backstage.framework.database.entity.Entity;

/**
 * @author sunyang
 * 
 * service的一些封装，其他service徐继承该service，提供一些对单表的查询，删除，修改等功能
 *
 */
public abstract class BaseService  {

	private static Logger log = Logger.getLogger(BaseService.class);


	/**
	 * @param 保存一条记录
	 * @return
	 */
	public <T extends Entity> void save(T t) {
		try {
			t.save();
		} catch (Exception e) {
			log.error("save fail " + e.getMessage());
			throw new RuntimeException("save fail " + e.getMessage());
		}
	}

	/**
	 * 保存多条记录
	 * 
	 * @param ts
	 */
	public <T extends Entity> void saveBatch(List<T> ts) {
		try {
			for(T t:ts){
				t.save();
			}
		} catch (Exception e) {
			log.error("save fail " + e.getMessage());
			throw new RuntimeException("save fail " + e.getMessage());
		}

	}

	public <T extends Entity> void updateField(Class<T> c, T t) {
		try {
			if (c.isAnnotationPresent(TableSeg.class)) {// 某个类是不是存在TableSeg注解
				TableSeg table = (TableSeg) c.getAnnotation(TableSeg.class);
				FormMap t_y = this.get(c, (String) t.get(table.id()));
				// 获取现在的属性
				String[] strs = t.getAttrNames();
				for(String s:strs)
					t_y.put(s, t.get(s));
				t.updateFull();
			}else{
				throw new Exception("cann't update beacuse" + c.getName() + " is not a entity table");
			}
		} catch (Exception e) {
			log.error("update fail " + e.getMessage());
			throw new RuntimeException("update fail " + e.getMessage());
		}
	}

	/**
	 * 将库里的字段按照该字段全量更新
	 * 
	 * @param t
	 */
	public <T extends Entity> void updateFull(T t) {
		try {
			t.updateFull();
		} catch (Exception e) {
			log.error("update fail " + e.getMessage());
			throw new RuntimeException("update fail " + e.getMessage());
		}
	}

	/**
	 * 按照单个删除
	 * 
	 * @param t
	 * @param id
	 */
	public <T extends Entity> void deleteById(Class<T> t, Object id) {
		try {
			if (t.isAnnotationPresent(TableSeg.class)) {// 某个类是不是存在TableSeg注解
				TableSeg table = (TableSeg) t.getAnnotation(TableSeg.class);
				T formMap = t.newInstance();
				formMap.put(table.id(), id);
				formMap.delete();
			} else {
				throw new Exception("cann't delete beacuse" + t.getName() + " is not a entity table");
			}
		} catch (Exception e) {
			log.error("delete fail " + e.getMessage());
			throw new RuntimeException("delete fail " + e.getMessage());
		}
	}
	
	
	/**
	 * 按照单个删除
	 * 
	 * @param t
	 * @param id
	 */
	public <T extends Entity> void deleteByIds(Class<T> t, String ... ids) {
		try {
			if (t.isAnnotationPresent(TableSeg.class)) {// 某个类是不是存在TableSeg注解
				TableSeg table = (TableSeg) t.getAnnotation(TableSeg.class);
				T formMap = t.newInstance();
				formMap.put("$in_"+table.id(), ids);
				formMap.delete();
			} else {
				throw new Exception("cann't delete beacuse" + t.getName() + " is not a entity table");
			}
		} catch (Exception e) {
			log.error("delete fail " + e.getMessage());
			throw new RuntimeException("delete fail " + e.getMessage());
		}
	}

	/**
	 * 根据对象的属性删除数据
	 * 
	 * @param t
	 */
	public void delete(Entity t) {
		try {
			t.delete();
		} catch (Exception e) {
			log.error("delete fail " + e.getMessage());
			throw new RuntimeException("delete fail " + e.getMessage());
		}
	}
	
	/**
	 * 
	 * load 如果没有数据将会返回错误
	 * @param c
	 * @param id
	 * @return
	 */
	public <T extends Entity> T  load(Class<T> c,Object id){
		try {
			if (c.isAnnotationPresent(TableSeg.class)) {// 某个类是不是存在TableSeg注解
				TableSeg table = (TableSeg) c.getAnnotation(TableSeg.class);
				T t = c.newInstance();
				t.put(table.id(), id);
				return (T) t.load();
			}else{
				throw new Exception("cann't get beacuse" + c.getName() + " is not a entity table");
			}
		}catch(Exception e){
			log.error("load fail " + e.getMessage());
			throw new RuntimeException("load fail " + e.getMessage());
		}
	}
	
	/**
	 * 
	 * 查询一个对象
	 * @param c
	 * @param id
	 * @return
	 */
	public <T extends Entity> T get(Class<T> c,Object id){
		try {
			if (c.isAnnotationPresent(TableSeg.class)) {
				TableSeg table = (TableSeg) c.getAnnotation(TableSeg.class);
				T t = c.newInstance();
				t.put(table.id(), id);
				return (T) t.queryOne();
			}else{
				throw new Exception("cann't get beacuse" + c.getName() + " is not a entity table");
			}
		}catch(Exception e){
			log.error("get fail " + e.getMessage());
			throw new RuntimeException("get fail " + e.getMessage());
		}
	}
	
	public <T extends Entity> List<T> queryList(T t){
		List<T> list = (List<T>) t.query();
		ServiceFactory.getCurrentSqlSession().clearCache();
		return list;
	}
	
	
	
	/**
	 * 查询全部的数据
	 * @param t 
	 * @return
	 */
	public <T extends Entity> List<T> queryAll(Class<T> t){
			T formMap;
			try {
				formMap = t.newInstance();
				return    (List<T>) formMap.query();
			} catch (InstantiationException | IllegalAccessException e) {
				e.printStackTrace();
			}
			return new ArrayList<>();
	}
	
	public <T extends Entity> List<T> findByPage(T t){
		return (List<T>) t.queryPage();
	}
	
	
	public  <T extends Entity> T convertFormMap(T t){
		
		String[] keys = t.getAttrNames();
		for(int i=0;i<keys.length;i++){
			Object value = t.get(keys[i]);
			if(value instanceof java.lang.String){
				value = ((java.lang.String) value).replace("'", "''");
				t.put(keys[i], value);
			}
		}
		return t;
		
	}
	
	/**
	 * 通过class 创建用户，不用new
	 * 
	 * @param clazz
	 * @return
	 */
	public  <T extends Entity> T  newFromMap(Class<T> clazz){
		try {
			return clazz.newInstance();
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
			throw new RuntimeException("create FormMap to error"+e.getMessage());
		}
	}
	
	public <T extends FormMap> T getOne(List<T> list){
		if(list!=null && list.size()>0){
			return list.get(0);
		}
		return null;
	}
	
	public List<String> getKeyValues(List<? extends FormMap> list,String key){
		List<String> ll = new ArrayList<>();
		if(list == null){
			return ll;
		}
		for(FormMap f:list){
			ll.add(f.getStr(key));
		}
		return ll;
	}
	
}
